package com.example.healthcondition.services.impl;


import com.example.healthcondition.entity.HealthReports;
import com.example.healthcondition.mapper.DietPlansMapper;
import com.example.healthcondition.mapper.ExerciseSuggestionsMapper;
import com.example.healthcondition.mapper.HealthReportsMapper;
import com.example.healthcondition.services.HealthReportsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Map;

@Service
public class HealthReportsServiceImpl implements HealthReportsService {

    private final DietPlansMapper dietPlansMapper;
    private final ExerciseSuggestionsMapper exerciseSuggestionsMapper;
    private final HealthReportsMapper healthReportsMapper;

    @Autowired
    public HealthReportsServiceImpl(DietPlansMapper dietPlansMapper,
                                    ExerciseSuggestionsMapper exerciseSuggestionsMapper,
                                    HealthReportsMapper healthReportsMapper) {
        this.dietPlansMapper = dietPlansMapper;
        this.exerciseSuggestionsMapper = exerciseSuggestionsMapper;
        this.healthReportsMapper = healthReportsMapper;
    }

    @Override
    public int generateHealthReport(Integer userId) {
        // 获取用户最新的饮食计划
        Map<String, Object> latestDietPlan = dietPlansMapper.findLatestByUserId(userId);
        // 获取用户最新的锻炼建议
        Map<String, Object> latestExerciseSuggestion = exerciseSuggestionsMapper.findLatestByUserId(userId);

        // 生成健康报告内容
        String overallHealth = "健康状态良好";
        StringBuilder recommendations = new StringBuilder();

        if (latestDietPlan != null) {
            recommendations.append("饮食计划：")
                    .append(latestDietPlan.get("description"))
                    .append("\n");
        }

        if (latestExerciseSuggestion != null) {
            recommendations.append("锻炼建议：")
                    .append(latestExerciseSuggestion.get("description"))
                    .append("\n");
        }

        // 创建健康报告对象
        HealthReports healthReport = new HealthReports();
        healthReport.setUserId(userId);
        healthReport.setReportDate(LocalDate.now());
        healthReport.setOverallHealth(overallHealth);
        healthReport.setRecommendations(recommendations.toString());

        // 保存健康报告到数据库
        int result= healthReportsMapper.insertHealthReport(healthReport);
        // 打印健康报告内容
        if (result > 0) {
            System.out.println("健康报告已成功保存到数据库，报告内容如下：");
            System.out.println(healthReport);
        } else {
            System.out.println("健康报告保存失败。");
        }

        return result;
    }
}